﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Beauty.BLL;
using Beauty.Model;
namespace WebUI.Models
{
    public class UtilWebService
    {
        picclassBLL classes = new picclassBLL();
        picalbumBLL albumBll = new picalbumBLL();
        collectionBLL bllCollect = new collectionBLL();
        picmainBLL bllPicMain = new picmainBLL();
        userBLL bllUser = new userBLL();
        public List<picclass> GetAllAlbumClass()
        {
            //加载类别
            List<picclass> list = classes.GetModelList("1=1 ORDER BY SortId");
            return list;
        }
        public int PageSize { get { return 10; } }
        /// <summary>
        /// 根据分类名称获取套图
        /// </summary>
        /// <param name="pinyin">要获取哪个分类下的套图(空或者all则获取全部套图)</param>
        /// <param name="list">分类集合对象</param>
        /// <param name="selectedClassName">选择的分类名字</param>
        /// <param name="enablePaging">分类集合对象</param>
        /// <param name="pageIndex">只有在分页开启时有效</param>
        /// <returns></returns>
        public List<picalbum> GetAlbumsByAction(string pinyin, List<picclass> list, out string selectedClassName, bool enablePaging, int pageIndex)
        {
            if (enablePaging)
            {
                pageIndex = (pageIndex - 1) * PageSize;
            }

            List<picalbum> albums;
            if (string.IsNullOrEmpty(pinyin) || pinyin.ToLower() == "all")
            {
                if (enablePaging)
                {
                    albums = albumBll.GetModelList("1=1 ORDER BY SortId DESC,AlbumId DESC LIMIT " + pageIndex + "," + PageSize);
                }
                else
                {
                    albums = albumBll.GetModelList("1=1 ORDER BY SortId DESC,AlbumId DESC ");
                }

                selectedClassName = "全部";
            }
            else
            {
                //取指定分类的套图

                var selectedAlbum = classes.GetModelList("PinYin='" + pinyin + "'");
                if (selectedAlbum.Count > 0)
                {
                    pinyin = classes.GetModelList("PinYin='" + pinyin + "'")[0].ClassId.ToString();//url地址输入是分类表的拼音 获取到此分类的id 下面根据id查套图
                    if (enablePaging)
                    {
                        albums = albumBll.GetModelList("ClassId=" + pinyin + " ORDER BY SortId DESC,AlbumId DESC LIMIT " + pageIndex + "," + PageSize);
                    }
                    else
                    {
                        albums = albumBll.GetModelList("ClassId=" + pinyin + " ORDER BY SortId DESC,AlbumId DESC");
                    }

                    selectedClassName = list.Where(c => c.ClassId.ToString() == pinyin).FirstOrDefault().ClassName;
                }
                else
                {
                    selectedClassName = "";
                    return null;
                }


            }

            foreach (var item in albums)
            {
                picmain pic = new picmainBLL().GetModel((int)item.CoverId);
                if (pic == null)
                {
                    //此套图的封面图片对象不存在 设置成默认的
                    item.CoverSrc = Settings.DefaultImg;
                }
                else
                {
                    item.CoverSrc = pic.Src;
                }
            }
            return albums;

        }

        /// <summary>
        /// 获得用户的收藏数据
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public List<collection> GetCollectionByUid(int uid)
        {
            //额外获取的数据 封面地址，收藏人数，套图内图片数量
            List<collection> cts = bllCollect.GetModelList("Uid=" + uid);
            foreach (var item in cts)
            {
                item.AlbumEntity = albumBll.GetModel((int)item.AlbumId);
                picmain pic = bllPicMain.GetModel((int)item.AlbumEntity.CoverId);
                if (pic == null)
                {
                    //此套图的封面图片对象不存在 设置成默认的
                    item.AlbumEntity.CoverSrc = Settings.DefaultImg;
                }
                else
                {
                    item.AlbumEntity.CoverSrc = pic.Src;

                    item.CollectionCount = bllCollect.GetRecordCount("AlbumId=" + item.AlbumId);
                    item.PicCount = bllPicMain.GetRecordCount("AlbumId=" + item.AlbumId);
                }
            }



            return cts;
        }
        /// <summary>
        /// 分页获得用户的收藏数据
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public List<collection> GetCollectionByUid(int uid, int index, int size)
        {
            //额外获取的数据 封面地址，收藏人数，套图内图片数量
            List<collection> cts = bllCollect.GetModelList("Uid=" + uid + " LIMIT " + index + "," + size);
            foreach (var item in cts)
            {
                item.AlbumEntity = albumBll.GetModel((int)item.AlbumId);
                picmain pic = bllPicMain.GetModel((int)item.AlbumEntity.CoverId);
                if (pic == null)
                {
                    //此套图的封面图片对象不存在 设置成默认的
                    item.AlbumEntity.CoverSrc = Settings.DefaultImg;
                }
                else
                {
                    item.AlbumEntity.CoverSrc = pic.Src;

                    item.CollectionCount = bllCollect.GetRecordCount("AlbumId=" + item.AlbumId);
                    item.PicCount = bllPicMain.GetRecordCount("AlbumId=" + item.AlbumId);
                }
            }



            return cts;
        }
        /// <summary>
        /// 获取套图的详细数据
        /// </summary>
        /// <param name="id">套图id</param>
        /// <param name="mains">所有图片对象</param>
        /// <param name="Recommends">推荐套图</param>
        /// <param name="picclass">所属分类对象</param>
        /// <param name="album">所属套图对象</param>
        public void GetAlbumDetialData(int id, out List<picmain> mains, out List<picalbum> Recommends, out picclass picclass, out picalbum album)
        {

            //获取指定套图id的所有图片
            picmainBLL mainBll = new picmainBLL();
            mains = mainBll.GetModelList("AlbumId=" + id + " ORDER BY PicId ASC", true); ;
            //获取套图信息
            if (mains.Count > 0)
            {
                album = albumBll.GetModel((int)mains[0].AlbumId);

                //获取套图所在分类
                picclass = classes.GetModel((int)album.ClassId);

                List<picclass> classesList = classes.DataTableToList(classes.GetAllList().Tables[0]);
                //获取分类下的4个相关推荐
                Recommends = albumBll.GetModelList("ClassId=" + album.ClassId + " AND AlbumId!=" + id + " ORDER BY  RAND() LIMIT 0,4");
                foreach (var item in Recommends)
                {
                    picmain pic = bllPicMain.GetModel((int)item.CoverId);
                    if (pic == null)
                    {
                        //此套图的封面图片对象不存在 设置成默认的
                        item.CoverSrc = Settings.DefaultImg;
                    }
                    else
                    {
                        item.CoverSrc = pic.Src;
                    }
                }


                //ViewData["classes"] = classesList;


                //ViewData["visted_albumid"] = aids;
                //ViewData["user"] = loginUser;

            }
            else
            {
                mains = null; Recommends = null; picclass = null; album = null;
            }

        }

        public ResData Upload(user user)
        {
            ResData res = new ResData();
            HttpFileCollection file = HttpContext.Current.Request.Files;

            foreach (var item in file.AllKeys)
            {
                HttpPostedFile head = file[item];
                try
                {
                    var supportedTypes = new[] { "jpg", "jpeg", "png", "gif", "bmp" };
                    var fileExt = System.IO.Path.GetExtension(head.FileName).Substring(1);
                    if (!supportedTypes.Contains(fileExt))
                    {
                        res.resCode = 201;
                        res.resMsg = "上传格式错误";
                        return res;
                    }

                    if (head.ContentLength > 1024 * 1000 * 10)
                    {
                        res.resCode = 201;
                        res.resMsg = "大小超出限制";
                        return res;
                    }

                    Random r = new Random();
                    var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt;
                    var filepath = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/Pic/user_headimg"), filename);
                    head.SaveAs(filepath);
                    //保存到磁盘上后 再更新到DB
                    if (SaveImgToDB(filename, user))
                    {
                        res.resCode = 200;
                        res.resMsg = "上传并修改头像成功";
                        res.resData = bllUser.GetModel(user.Uid).IconUrl;
                    }
                    else
                    {
                        res.resCode = 201;
                        res.resMsg = "保存到数据库中失败";
                    }


                }
                catch (Exception ex)
                {
                    res.resCode = 500;
                    res.resMsg = ex.Message;

                    return res;
                }
            }


            if (res == null)
            {
                res.resCode = 400;
                res.resMsg = "上传文件为空";
                return res;
            }
            else
            {
                return res;
            }


        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="user">要修改的用户</param>
        /// <param name="nowpass">当前密码，用于校验</param>
        /// <param name="newpass">新密码</param>
        /// <returns></returns>
        public ResData ChangePass(user user, string nowpass, string newpass)
        {
            ResData res = new ResData();
            if (!user.UPass.Equals(nowpass))
            {
                res.resCode = 201;
                res.resMsg = "当前密码输入错误";
            }
            else
            {
                user.UPass = newpass;
                if (bllUser.Update(user))
                {
                    res.resCode = 200;
                    res.resMsg = "修改成功";
                }
                else
                {
                    res.resCode = 201;
                    res.resMsg = "修改失败";
                }
            }
            return res;


        }
        private bool SaveImgToDB(string filename, user user)
        {
            user.IconUrl = "/Pic/user_headimg/" + filename;
            return bllUser.Update(user);
        }
    }



    public class Settings
    {

        //public string DefaultImg = s;// "http://www.jianchazhan.cn/UploadFiles/defualt/default-service.jpg";
        public static string DefaultImg
        {
            get
            {
                return System.Configuration.ConfigurationManager.AppSettings["DefaultImg"].ToString(); ;
            }
        }

    }
}